package com.huynv.thetopnews;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.app.Dialog;

import java.io.IOException;
import java.lang.Thread;





import android.webkit.WebChromeClient;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebViewClient;
import android.webkit.WebView;
import android.graphics.Bitmap;
import android.widget.ProgressBar;
import android.view.MenuItem;
import android.view.View;
import android.view.KeyEvent;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;


import com.huynv.thetopnews.R;

import android.widget.LinearLayout;
import android.view.*;
import android.widget.RelativeLayout;
import android.graphics.Point;
import android.app.ActionBar;
import android.widget.ShareActionProvider;
public class viewWeb extends Activity{
	public String urlGetDetailNews=Config.domain+"/Home/getDetailNews?id=";
	private Thread thread;
	private Boolean loadingFinished=false;
	private Boolean redirect=false;
	private jsonParseDetail jsonP;
	private TextView title;
	private TextView des;
	private WebView fullContent;
	private WebSettings fullContentsettings;
	private ProgressDialog dialog;
	private String link="";
	private String DATA_STRING="";
	private AdView adView;
	private static final String AD_UNIT_ID = "ca-app-pub-6575239088642506/7605082471";//"a153350bf490de1";
	private AlertDialog alertDialog;
	public int maxDelay=20000;
	public long oldTime=0;
	public boolean loading=true;
	private ActionBar actionBar;
	private ShareActionProvider mShareActionProvider;
	ProgressBar Pbar;
	public boolean is_Single_Colunm=false;
	private int maxSdk=19;
	@Override
	protected void onCreate(Bundle savedInstanceState) {		
		super.onCreate(savedInstanceState);			
		setContentView(R.layout.view_detail);
		actionBar = getActionBar();
		actionBar.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg));
		//Log.e("viewWeb","ok1");
		Intent intent = getIntent();
		//Log.e("viewWeb","ok2");
		link=intent.getStringExtra("link");
		link=Utils.removeSC(link);
		//Log.e("viewWeb","ok3, link="+link);
		String id=intent.getStringExtra("id");
		
		Pbar = (ProgressBar) findViewById(R.id.pB1);
		fullContent = (WebView) findViewById(R.id.webview);	
		fullContent.getSettings().setSupportZoom(true);
        
    	fullContent.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    	fullContent.setScrollbarFadingEnabled(true);
    	fullContent.getSettings().setLoadsImagesAutomatically(true);        
    	fullContent.getSettings().setLoadWithOverviewMode(true);

//    	if (!link.contains("latimes.com")){
//	    	fullContent.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
//			is_Single_Colunm=true;			
//    	}else{
	    	if (Build.VERSION.SDK_INT<maxSdk){
	    		fullContent.getSettings().setLayoutAlgorithm(LayoutAlgorithm.NARROW_COLUMNS);
				
	    	}
    	//}
	    is_Single_Colunm=false;	
		fullContent.getSettings().setUseWideViewPort(true);
		//.setUseWideViewPort(true);
		fullContent.getSettings().setBuiltInZoomControls(true);
		//fullContent.getSettings().setPluginState(PluginState.ON);
		fullContent.setWebViewClient(new myWebClient());
		fullContent.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress) 
            {
            if(progress < 100 && Pbar.getVisibility() == ProgressBar.GONE){
                Pbar.setVisibility(ProgressBar.VISIBLE);
                //txtview.setVisibility(View.VISIBLE);
            }
            Pbar.setProgress(progress);
            if(progress == 100) {
                Pbar.setVisibility(ProgressBar.GONE);
                //txtview.setVisibility(View.GONE);
            }
         }
		});
		
		//Log.e("onCreate", "ok3");
		fullContent.getSettings().setJavaScriptEnabled(true);
		fullContentsettings=fullContent.getSettings();
		
		//title = (TextView) findViewById(R.id.titleDetail);
		//Log.e("viewWeb","ok4");
		//des = (TextView) findViewById(R.id.desDetail);
		//Log.e("viewWeb","ok5");
			
		//dialog = ProgressDialog.show(this, "thetopnews.net","Loading...", true);		
		if (Build.VERSION.SDK_INT<maxSdk){
			new showNewsFromUrlTask().execute(link);
		}
		else
		{
			fullContentsettings.setLayoutAlgorithm(LayoutAlgorithm.NORMAL);
			fullContent.loadUrl(link);
		}
		
        adView = new AdView(this);
	    adView.setAdSize(AdSize.BANNER);	   
	    adView.setAdUnitId(AD_UNIT_ID);
	    RelativeLayout rl = new RelativeLayout(this);
	    RelativeLayout.LayoutParams lay = new RelativeLayout.LayoutParams(
	        RelativeLayout.LayoutParams.FILL_PARENT, 
	        RelativeLayout.LayoutParams.WRAP_CONTENT);
	    lay.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);	    
	    RelativeLayout layout = (RelativeLayout) findViewById(R.id.layoutWeb);
	    layout.addView(adView,lay);
	    AdRequest adRequest = new AdRequest.Builder().build();
	    adView.loadAd(adRequest);
	}
	private class showNewsFromUrlTask extends AsyncTask<String, Void, String> {    	
        @Override
        protected String doInBackground(String... urls) {              
            // params comes from the execute() call: params[0] is the url.
            try {
            	
        		//Log.e("onCreate", "ok4");
        		fullContent.loadUrl(urls[0]);
                return "1";	
            } catch (Exception e) {
            	Log.e("showNewsFromUrlTask", "can not download");
            	//dialog.dismiss();
            	showExtProgram("Internet connection","Internet connection not available!");
            	//ResultDownloadWebpage=0;            	
            	return "0";
            }
        }
        
        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
            //textView.setText(result);
        	//try{
        		//if(dialog!=null) dialog.dismiss();
        	//}catch(Exception ex){
        		
        	//}
        	if (result.equals("0")){ 
        		Log.e("onPostExecute", "can not download");
        		showExtProgram("Internet connection","Internet connection not available!");
        	}else{        		
        		Log.e("onPostExecute", "ok");
        	}
        	//try{
        		//if(dialog!=null) dialog.dismiss();
        	//}catch(Exception ex){
        		
        	//}
       }
    }
public void showExtProgram(String title,String message){
		
		AlertDialog.Builder builder = new AlertDialog.Builder(this);

    	// 2. Chain together various setter methods to set the dialog characteristics
    	builder.setMessage(message)
    	       .setTitle(title)
    	       .setCancelable(false)
			   .setPositiveButton("Exit",new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,int id) {
						// if this button is clicked, close
						// current activity							
						//viewWeb.this.finish();
				    	//System.exit(0);
					}
				 });

    	// 3. Get the AlertDialog from create()
    	alertDialog= builder.create();
    	alertDialog.show();
	}
	public class myWebClient extends WebViewClient
	{
	
	     @Override
		 public void onPageStarted(WebView view, String url,Bitmap favicon) {
	      // TODO Auto-generated method stub
	      Log.e("onPageStarted", "ok1");
	      super.onPageStarted(view, url,favicon);	
	      Log.e("onPageStarted", "ok2");
	     }	 	
	     @Override	
	     public boolean shouldOverrideUrlLoading(WebView view, String url) {
	      // TODO Auto-generated method stub
	      Log.e("shouldOverrideUrlLoading", "ok1");
	      view.loadUrl(url);
	      Log.e("shouldOverrideUrlLoading", "ok2");
	      return true;
	     }
	     @Override	
	     public void onPageFinished(WebView view, String url) {
	      // TODO Auto-generated method stub
	      //Log.e("onPageFinished", "ok1");
	      super.onPageFinished(view, url);
	      //Log.e("onPageFinished", "ok2");
	      //progressBar.setVisibility(View.GONE);
	      //loading=false;
	      //dialog.dismiss();
	      //Log.e("onPageFinished", "ok3");
//	      fullContentsettings.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);    		
//		  fullContentsettings.setUseWideViewPort(false);
//		  is_Single_Colunm=true;
	     }
	  }
	@Override	
	 public boolean onKeyDown(int keyCode, KeyEvent event)	
	 {	
	  if ((keyCode == KeyEvent.KEYCODE_BACK) && fullContent.canGoBack()) {	
		  fullContent.goBack();	
		  return true;
	  }
	  return super.onKeyDown(keyCode, event);
	 }
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    // Inflate menu resource file.
		//Log.e("aaaaaaaaaaaaaaaaa","onCreateOptionsMenu1");
	    getMenuInflater().inflate(R.menu.menu_share, menu);
	    //Log.e("aaaaaaaaaaaaaaaaa","onCreateOptionsMenu2");
	    // Locate MenuItem with ShareActionProvider
	    //MenuItem item = menu.findItem(R.id.menu_item_share);
	    //Log.e("aaaaaaaaaaaaaaaaa","onCreateOptionsMenu3");
	    // Fetch and store ShareActionProvider
	    //mShareActionProvider = (ShareActionProvider) item.getActionProvider();
	    //Log.e("aaaaaaaaaaaaaaaaa","onCreateOptionsMenu4");
	    //mShareActionProvider.setShareIntent(this.getIntent());
	    // Return true to display menu
	    //if (link.contains("latimes")){
			//fullContent.getSettings().setLayoutAlgorithm(LayoutAlgorithm.NARROW_COLUMNS);
			//is_Single_Colunm=false;
			//MenuItem item=(MenuItem) findViewById(R.id.menu_item_full_screen);
			//item.setIcon(R.drawable.normal_screen);
	    //}
	    return true;
	    //return super.onCreateOptionsMenu(menu);
	}
	@Override
    public boolean onOptionsItemSelected(MenuItem item)
    {    
		//Log.e("aaaaaaaaaaaaaaaaa",String.valueOf(item.getItemId()));
        switch (item.getItemId())
        {	
        	case R.id.menu_item_share:
        		//HomePage();
        		//Log.e("aaaaaaaaaaaaaaaaa","1");
        		String message = this.link;
        				Intent share = new Intent(Intent.ACTION_SEND);
        				share.setType("text/plain");
        				share.putExtra(Intent.EXTRA_TEXT, message);
        				startActivity(Intent.createChooser(share, "Share link"));
        		//Log.e("aaaaaaaaaaaaaaaaa","2");
            return true;   
        	case R.id.menu_item_back:
        		this.finish();
            return true; 
        	case R.id.menu_item_increase_font:
        		//WebSettings fullContentsettings = fullContent.getSettings();
        		fullContentsettings.setTextZoom( (int)(fullContentsettings.getTextZoom() * 1.1) );
        		return true;  
        	case R.id.menu_item_full_screen:
        		//WebSettings fullContentsettings = fullContent.getSettings();
    			if (is_Single_Colunm){
    				if (Build.VERSION.SDK_INT<maxSdk){
    					fullContentsettings.setLayoutAlgorithm(LayoutAlgorithm.NARROW_COLUMNS);  
    				} else{
    					fullContentsettings.setLayoutAlgorithm(LayoutAlgorithm.NORMAL); 
    				}   		
    				fullContentsettings.setUseWideViewPort(true);
    				item.setIcon(R.drawable.normal_screen);
    				item.setTitle("Zoom out images");
    				is_Single_Colunm=false;
        		}else{
        			if (Build.VERSION.SDK_INT<maxSdk){
        				fullContentsettings.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN); 
        			}else{
    					fullContentsettings.setLayoutAlgorithm(LayoutAlgorithm.NORMAL); 
    				}	
    				fullContentsettings.setUseWideViewPort(true);
    				item.setIcon(R.drawable.full_screen);
    				item.setTitle("Zoom in images");
    				is_Single_Colunm=true;
        		}
    			return true;
        	default:
            return super.onOptionsItemSelected(item);
        }
    }   
	// Call to update the share intent
//	private void setShareIntent(Intent shareIntent) {
//		 Log.e("aaaaaaaaaaaaaaaaa","setShareIntent1");
//		shareIntent=new Intent(Intent.ACTION_SEND);
//		shareIntent.setType("text/plain");
//		shareIntent.putExtra(Intent.EXTRA_TEXT, "https://www.facebook.com/sharer/sharer.php?u="+this.link);
//		 Log.e("aaaaaaaaaaaaaaaaa","setShareIntent2");
//		startActivity(shareIntent);
//		 Log.e("aaaaaaaaaaaaaaaaa","setShareIntent3");
////	    if (mShareActionProvider != null) {
////	        mShareActionProvider.setShareIntent(shareIntent);
////	    }
//	    
//	    
//	}
	
}
